/*
		ServEngine framework library
		A library to fast develop JEE online applications
	
		Copyright 2008 José Ignacio de Córdoba Álvaro

		Licensed under the Apache License, Version 2.0 (the "License");
		you may not use this file except in compliance with the License.
		You may obtain a copy of the License at

				http://www.apache.org/licenses/LICENSE-2.0

		Unless required by applicable law or agreed to in writing, software
		distributed under the License is distributed on an "AS IS" BASIS,
		WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
		See the License for the specific language governing permissions and
		limitations under the License.
	
		Jose Ignacio de Cordoba Alvaro
		http://ignacio.decordoba.com
*/

package com.servengine;

import com.servengine.entry.EntryManagerLocal;
import com.servengine.user.UserManagerLocal;

import java.lang.reflect.Field;

import javax.servlet.*;
import com.servengine.portal.*;

import java.beans.IntrospectionException;

import javax.naming.Context;

abstract public class ServletContextClient implements javax.servlet.ServletContextListener
{
  private static org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog( ServletContextClient.class.getName() );
	protected ServletContext servletContext;
//	protected StatelessUtilsLocal statelessutils;
	protected PortalManagerLocal portalmanager;
	protected UserManagerLocal usermanager;
	protected EntryManagerLocal entryManager;
//	protected javax.naming.Context context;	
	public void contextInitialized(ServletContextEvent sce)
	{
//		String url=null;
		try
		{
			servletContext = sce.getServletContext();
/*			Properties properties = new Properties();
			try
			{
				properties.load(getClass().getClassLoader().getResourceAsStream("jbossclienturls.properties"));
			} catch (NullPointerException e)
			{
				log.warn("ClassLoader can't load jbossclienturls.properties");
			}
		  url = properties.getProperty(getClass().getName());
		  if (url==null)
		    url = properties.getProperty("default");			
		  if (url==null)
		  {
		    url="jnp://localhost:1099/"+servletcontext.getServletContextName();
		    servletcontext.log("No default url found. Defaults to localhost JBoss url with ServletContextName: "+servletcontext.getServletContextName());
		    servletcontext.log(url);
		  }

			log.info("java.naming.provider.url="+url);
			java.util.Hashtable<String,String> props = new java.util.Hashtable<String,String>();
			props.put("java.naming.factory.initial", "org.jnp.interfaces.NamingContextFactory");
			props.put("java.naming.provider.url", url);
			props.put(javax.naming.Context.URL_PKG_PREFIXES,"org.jboss.naming:org.jnp.interfaces");
			initialcontext = new javax.naming.InitialContext(props);*/
			javax.naming.Context context = (Context)new javax.naming.InitialContext().lookup(servletContext.getServletContextName());	
			createManagers(context);
		  bindObjectInServletContext();
			clientInitialized(context);
		  log.info(getClass().getName()+" binded to ServletContext.");
//			log.info(getClass().getName()+" binded to application as "+getServletContextAttributeName());
		}	catch(RuntimeException e)
		{
			log.error("ServletContextUtils: RuntimeException: ",e);
			throw e;
		}
		catch (Exception e)
		{
			log.error("ServletContextUtils: Exception: ",e);
			throw new IllegalStateException(e.getMessage());
		}
		log.info("contextInitialized");
	}
	public void contextDestroyed(ServletContextEvent sce)
	{
		clientDestroyed();
		log.info(getClass().getName()+/*" ("+getServletContextAttributeName()+*/" out of the application");
	}

	protected void bindObjectInServletContext() throws IntrospectionException
	{
		try
		{
			Field field = getClass().getField("SERVLETCONTEXT_ATTRIBUTE_NAME");
			String servletContextAttributeName = (String)field.get(this);
		  servletContext.setAttribute(servletContextAttributeName,this);
		} catch (Exception e)
		{
			log.error(e.getMessage(),e);
		}
/*		for (PropertyDescriptor propertyDescriptor: Introspector.getBeanInfo( this.getClass()).getPropertyDescriptors())
			if (propertyDescriptor.getName().equals("servletContextAttributeName"))
			{
				java.lang.reflect.Method getter = propertyDescriptor.getReadMethod();
				try
				{
					String servletContextAttributeName = (String)getter.invoke(this,null);
					servletcontext.setAttribute(servletContextAttributeName,this);
				} catch (Throwable e)
				{
					log.error(e.getMessage(),e);
				}
				return;
			}
		log.warn("No such property in Class: servletContextAttributeName");*/
	}

	protected void createManagers(Context context) throws javax.naming.NamingException,javax.ejb.CreateException,java.rmi.RemoteException
	{
//	  statelessutils = ((StatelessUtilsHome)initialcontext.lookup("StatelessUtils")).create();
	  portalmanager = (PortalManagerLocal)context.lookup("PortalManager/local");
	  usermanager = (UserManagerLocal)context.lookup("UserManager/local");
	  try
		{
			entryManager = (EntryManagerLocal)context.lookup("EntryManager/local");
		} catch (Throwable e)
		{
			if (log.isDebugEnabled())
				log.debug("entryManager not found: ",e);
			else
				log.warn("entryManager not found:"+e.getMessage());
		}
	}
/*	static public String getServletContextAttributeName()
	{
		String className = new Exception().getStackTrace()[0].getClassName();
//		String className = new CurrentClassGetter().getClassName();
		return className;
	}
	public static class CurrentClassGetter extends SecurityManager {
		public String getClassName() {
			return getClassContext()[1].getName();
		}
	}*/
		
	abstract protected void clientInitialized(javax.naming.Context context);
	abstract protected void clientDestroyed();
}